package xyz.yuzegod.megawalls.game.stage;

import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import xyz.yuzegod.megawalls.MegaWalls;
import xyz.yuzegod.megawalls.game.Game;

import java.util.HashMap;
import java.util.Map;

public class StageManager implements Runnable
{
    private Game game;
    private int taskId;
    private int currentStage;
    private int seconds;
    private Map<Integer, GameStage> stages;
    
    public StageManager(final Game game) {
        this.taskId = 0;
        this.currentStage = 0;
        this.seconds = 0;
        this.stages = new HashMap<Integer, GameStage>();
        this.game = game;
        this.registerStage(new ProtectStage());
        this.registerStage(new WallFallStage());
        this.registerStage(new WitherAngryStage());
        this.registerStage(new DeathMatchStage());
        this.registerStage(new BattleStage());
        this.registerStage(new OverStage());
    }
    
    @Override
    public void run() {
        final GameStage stage = this.currentStage();
        if (this.seconds >= stage.getExcuteSeconds()) {
            this.setCurrentStage(stage.getPriority() + 1);
            stage.excute(this.game);
        }
        else if (stage.getExcuteLeftSeconds() >= stage.getExcuteSeconds() - this.seconds) {
            stage.excuteLeftSeconds(this.game, stage.getExcuteSeconds() - this.seconds);
        }
        ++this.seconds;
    }
    
    public GameStage currentStage() {
        return this.stages.getOrDefault(this.currentStage, null);
    }
    
    public void setCurrentStage(final int priority) {
        this.seconds = 0;
        this.currentStage = priority;
    }
    
    public int getSeconds() {
        return this.seconds;
    }
    
    public void setSeconds(final int seconds) {
        this.seconds = seconds;
    }
    
    public int getLeftTime() {
        return this.currentStage().getExcuteSeconds() - this.seconds;
    }
    
    public String formattedNextStage() {
        final GameStage currentStage = this.currentStage();
        final String color = (this.getLeftTime() <= 30) ? ((this.getLeftTime() % 2 == 0) ? "§a" : "§c") : "§a";
        return "§f" + currentStage.getName() + "： " + color + this.game.getFormattedTime(this.getLeftTime());
    }
    
    private void registerStage(final GameStage event) {
        this.stages.put(event.getPriority(), event);
    }
    
    public GameStage getStage(final int priority) {
        return this.stages.getOrDefault(priority, null);
    }
    
    public void start() {
        if (this.taskId != 0) {
            return;
        }
        Bukkit.getScheduler().runTaskTimer((Plugin)MegaWalls.getInstance(), (Runnable)this, 0L, 20L);
    }
    
    public void stop() {
        if (this.taskId == 0) {
            return;
        }
        Bukkit.getScheduler().cancelTask(this.taskId);
        this.taskId = 0;
        this.currentStage = 0;
        this.seconds = 0;
    }
}
